<template>
  <div class="room-manage-container">
    <el-card class="page-container">
      <template #header>
        <div class="header">
          <span>我的房间管理</span>
          <el-button type="primary" @click="openCreateRoomDrawer">新增房间</el-button>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="error" class="error-container">
        <el-empty :description="errorMessage">
          <template #extra>
            <el-button type="primary" @click="initData">重试</el-button>
          </template>
        </el-empty>
      </div>
      
      <div v-else>
        <el-table v-if="tableData.length > 0" :data="tableData" stripe style="width: 100%">
          <el-table-column prop="roomType" label="房型"/>
          <el-table-column prop="price" label="价格"/>
          <el-table-column prop="availableCount" label="可用数量"/>
          <el-table-column prop="breakfast" label="含早">
            <template #default="{ row }">
              {{ row.breakfast === '1' ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template #default="{ row }">
              <el-button type="primary" :icon="Edit" circle @click="openUpdateRoomDrawer(row)"/>
              <el-button type="danger" :icon="Delete" circle @click="handleDelete(row.roomType, row.hotelName)"/>
            </template>
          </el-table-column>
        </el-table>
        
        <el-empty v-else description="暂无房间数据">
          <template #extra>
            <el-button type="primary" @click="openCreateRoomDrawer">添加房间</el-button>
          </template>
        </el-empty>
      </div>
      
      <create-room ref="createRoomRef" @refresh="initData" :fixed-hotel="hotelName"/>
      <update-room ref="updateRoomRef" @refresh="initData"/>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getRoomsByHotel, deleteRoom } from '@/api/room'
import { Edit, Delete } from '@element-plus/icons-vue'
import CreateRoom from '../room/components/CreateRoom.vue'
import UpdateRoom from '../room/components/UpdateRoom.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getHotelByUserId } from '@/api/hotel'
import { useUserInfoStore } from '@/stores/userInfo'

const tableData = ref([])
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('获取房间列表失败')
const createRoomRef = ref()
const updateRoomRef = ref()
const userInfoStore = useUserInfoStore()
const hotelName = ref('')

const initData = async () => {
  if (!userInfoStore.userInfo || !userInfoStore.isHotelOwner()) {
    errorMessage.value = '您没有访问此页面的权限'
    error.value = true
    loading.value = false
    return
  }
  
  loading.value = true
  error.value = false
  
  try {
    // 先获取用户关联的酒店
    const userId = userInfoStore.userInfo.user.userId
    const hotelRes = await getHotelByUserId(userId)
    const hotelResult = hotelRes.data
    
    if (hotelResult && hotelResult.code === 200 && hotelResult.data) {
      hotelName.value = hotelResult.data.hotelName
      
      // 获取该酒店的房间列表
      const res = await getRoomsByHotel(hotelName.value)
      const result = res.data
      
      if (result && result.code === 200) {
        tableData.value = Array.isArray(result.data) ? result.data : []
      } else {
        error.value = true
        errorMessage.value = result?.msg || '获取房间列表失败'
      }
    } else {
      error.value = true
      errorMessage.value = hotelResult?.msg || '获取酒店信息失败'
    }
  } catch (err) {
    console.error('获取房间列表错误:', err)
    error.value = true
    errorMessage.value = '网络错误，获取房间列表失败'
  } finally {
    loading.value = false
  }
}

const openCreateRoomDrawer = () => {
  if (!hotelName.value) {
    ElMessage.warning('无法获取酒店信息，请先创建酒店')
    return
  }
  createRoomRef.value.open()
}

const openUpdateRoomDrawer = (row: any) => {
  updateRoomRef.value.open(row)
}

const handleDelete = (roomType: string, hotelName: string) => {
  if (!roomType || !hotelName) {
    ElMessage.error('房型和酒店名称不能为空')
    return
  }
  
  ElMessageBox.confirm('确定要删除该房间吗？', '提示', { type: 'warning' }).then(() => {
    deleteRoom(roomType, hotelName).then(res => {
      const result = res.data
      if (result && result.code === 200) {
        ElMessage.success('删除成功')
        initData()
      } else {
        ElMessage.error(result?.msg || '删除失败')
      }
    }).catch(error => {
      console.error('删除房间错误:', error)
      ElMessage.error('网络错误，删除房间失败')
    })
  }).catch(() => {
    // 用户取消删除操作
  })
}

onMounted(() => {
  initData()
})
</script>
<style scoped>
.room-manage-container {
  padding: 20px;
}

.page-container {
  min-height: 600px;
}
.header { 
  display: flex; 
  justify-content: space-between; 
  align-items: center;
}
.loading-container, .error-container {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style> 